package temp;

import java.io.File;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.TimerTask;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;

import src.RTPpacket;

public class SendTask extends TimerTask{
	

	
	private DatagramPacket current;
	private DatagramSocket datagramSocket;
	private AudioInputStream audioStream;
	private InetAddress clientAddress;
	private AudioFormat format;
	private int clientPort;
	private File file;
	private int payloadSizeInBytes;
	private int nextSeqNum;
	
	public SendTask(String fileName,int clientPort,InetAddress clientAddress) {
		try {
			datagramSocket = new DatagramSocket(Constants.SERVER_UDP_PORT);
			this.clientAddress = clientAddress;
			file = new File(fileName);
			audioStream = AudioSystem.getAudioInputStream(file);
			format = audioStream.getFormat();
			double frameRate = format.getFrameRate();
	        double frameSize = format.getFrameSize();
	        double byteRate = frameRate*frameSize; 
	        payloadSizeInBytes = (int) (byteRate*(Constants.PAYLOAD_LENGTH_IN_MILISECONDS/1000.0));
	        nextSeqNum = 0;
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		try {
			//le o stream e cria um rtpPacket
			byte[] payload = new byte[payloadSizeInBytes];
			int byteReads = audioStream.read(payload,0,payload.length);
			
			RTPpacket rtpPacket = new RTPpacket(payload,byteReads);
			rtpPacket.SequenceNumber = nextSeqNum++;
			
			//rtpPacket in bytes
			int packetLength = rtpPacket.getlength();
			byte[] bitsPacket = new byte[packetLength];
			rtpPacket.getpacket(bitsPacket);
			
			//cria e envia o datagram packet
			current = new DatagramPacket(bitsPacket,packetLength,this.clientAddress,clientPort);
			datagramSocket.send(current);
			
		} catch (Exception e) {

		}
	}

}
